package com.wholesale.commons;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.StatFs;
import android.view.inputmethod.InputMethodManager;

public class CommonUtil {

	/**
	 * 获取SD卡可用的内存
	 * @return
	 */
	public static long getSDSize(){
		String str = Environment.getExternalStorageDirectory().getPath();
		StatFs localStatFs = new StatFs(str);
		long l = localStatFs.getBlockSize();
		return localStatFs.getAvailableBlocks()*l;
	}
	
	/**
	 * 保存图片
	 * @param bitmap
	 * @param path
	 * @param fileName
	 */
	public static void saveFile(Bitmap bitmap,String path,String fileName){
		File filePath = new File(path);
		if(!filePath.exists()){
			filePath.mkdirs();
		}
		String fileFullPath = String.valueOf(path)+fileName;
		File file = new File(fileFullPath);
		try {
			FileOutputStream fos = new FileOutputStream(file);
			BufferedOutputStream bos = new BufferedOutputStream(fos);
			if(bitmap!=null){
				Bitmap.CompressFormat compressFormat = Bitmap.CompressFormat.PNG;
				bitmap.compress(compressFormat, 100, bos);
				bos.flush();
				bos.close();
			}
			return ;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Drawable ת bitmap
	 * @param d
	 * @return
	 */
	public static Bitmap drawableToBitmap(Drawable d){
		Bitmap bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), d.getOpacity()!=PixelFormat.OPAQUE?Bitmap.Config.ARGB_8888:Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
		d.draw(canvas);
		return bitmap;
	}
	
	public static byte[] bitmapToBytes(Bitmap bitmap){
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}
	
	public static Bitmap bytesToBitmap(byte[] bytes){
		if(bytes.length!=0){
			return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		}else{
			return null;
		}
	}
	
	public static void isActive(Activity activity){
		InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);  
		if (imm.isActive()){
			imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS); 
		}
	}
	
}
